/**
 * This File works as the utility for the gloaba page BrowerSide
 * Haveing String Extendtion
 * Haveing Utilities of components like file upload plugin table generator ec.
 *@author Kun.Huang 
 *@email : huangkun85@gmail.com
 *@student ID: a1184863
 *@Date: 29/5/2013
 *@LastUpdateDate:10/6/2013
 */

/**
 * The overwite of String format function for javascript
 * @param {type} src
 * @returns {@exp;src@call;replace}
 */
String.format = function(src) {
    if (arguments.length === 0)
        return null;
    var args = Array.prototype.slice.call(arguments, 1);
    return src.replace(/\{(\d+)\}/g, function(m, i) {
        return args[i];
    });
};
/*
 * The Current Controller
 * @type Controller_Secretary|Controller_Advisor|Controller_Faculty
 */
var currentController = {};
/////////////////////////////////
// Debug Module Start From Here 
// A debug Div is required
/////////////////////////////////
var Trace = {};
Trace.isDebug = true;
/**
 * direct output with the data
 * support second color as the the color option
 * @param {type} data
 * @returns {undefined} */
Trace.debugOutput = function(data) {
    if (this.isDebug) {
        var color = '#ff0000';
        if (arguments.length > 1)
        {
            color = arguments[1];
        }
        var outputformat = "<p style='color: {0}'>{1}</p><hr>";
        $("#debugDiv").append(String.format(outputformat, color, data));
    }
};

/**
 * Debug ouput the Object properties
 * Support the color setting as the second param 
 * Kun.Huang
 * 15/5/2013
 * @param {type} Object
 */
Trace.debugJsObject = function(Object)
{
    if (this.isDebug) {
        var output = '';
        for (property in Object) {
            output += property + ': ' + Object[property] + '<br/> ';
        }
        var color = '#f0f00';
        if (arguments.length > 1)
        {
            color = arguments[1];
        }
        var outputformat = "<p style='color: {0}'>{1}</p><hr>";
        $("#debugDiv").append(String.format(outputformat, color, output));
    }
};

/**
 * Debug  a Javascript Array[Objects]
 * @param {type} data
 * @returns {undefined}
 */
Trace.debugJsObjectData = function(data)
{
    if (this.isDebug) {
        var color = "#868";
        if (arguments.length > 1)
        {
            color = arguments[1];
        }
        for (var i = 0; i < data.length; i++)
        {
            // the this is in the Trace Object instance
            this.debugJsObject(data[i], color);
        }
    }
};

/**
 * To handle the fail Response
 * @param {type} data
 * @returns {undefined}
 */
Trace.debugFailResponse = function(data)
{
    var output = '';
    output += data.responseText + '<br/>';
    output += data.status + '<br/>';
    output += data.statusText + '<br/>';
    $("#debugDiv").append("<p  style='color: #ff0000'>" + output + "</p>" + '<hr>');
};


////////////////////////////////////
//Application general use
/////////////////////////////////
var CPS = new Object();

/**
 * get the System Setting
 * @param {type} index
 * @returns {Number}
 */
CPS.getSystemSetting = function(index)
{
    var res = null;
    if (index === "ElaspeDayAlarm")
    {
        res = 3;
    }
    return res;
};

/**
 * Get the Url Parameter Key value
 * @returns {Object}
 */
CPS.getUrlParmeters = function()
{
    var args = new Object();
    var query = location.search.substring(1);
    var pairs = query.split("&");
    for (var i = 0; i < pairs.length; i++)
    {
        var pos = pairs[i].indexOf('=');
        // if can not find then next    
        if (pos === -1) {
            continue;
        }
        var argname = pairs[i].substring(0, pos);
        var value = pairs[i].substring(pos + 1);
        args[argname] = unescape(value);
    }
    return args;
};


/**
 * To parse the String to the currunt controller's method
 * @param {String} strAction
 * @returns {Non-return}
 */
CPS.parseActionString = function(strAction)
{
    var strAction = strAction.split("|");
    // rebuild the javascript function
    var format = String.format("currentController.{0}(", strAction[0]);
    for (var i = 1; i < strAction.length; i++)
    {
        format += String.format("\"{0}\",", strAction[i]);
    }
    // remove the final ','
    format = format.substr(0, format.length - 1);
    format += ");";
    eval(format);
};

/**
 * To Set the login Infor Bar
 * @param {type} callback
 * @returns {undefined}
 */
CPS.setLoginInfoBar = function(callback)
{
    var logininforSelector = "#pagehead-LoginInfo";
    var format = "{0},You are Login As [{1}] of School({2})";
    $(logininforSelector).html(String.format(format, this.getUserName(), this.getRoleName(), this.getSchoolName()));
    $(logininforSelector).fadeIn(3000, callback);
};

/**
 * get the Time Stamp AS UUID
 * @returns {A Unique String }
 */
CPS.getTimeStamp = function()
{
    return new Date().getTime().toString();
};
/**
 * Return the session ID
 * @returns {@exp;@call;$@call;val}
 */
CPS.getSessionID = function()
{
    return $("#SESSION_ID").val();
};
/**
 * Set the session ID
 * @param {type} sessionId
 * @returns {@exp;@call;$@call;val}
 */
CPS.setSessionID = function(sessionId)
{
    return $("#SESSION_ID").val(sessionId);
};

CPS.getUserID = function()
{
    return $("#User_ID").val();
};

CPS.setUserID = function(UserID)
{
    $("#User_ID").val(UserID);
};

CPS.getUserName = function()
{
    return $("#User_Name").val();
};

CPS.setUserName = function(UserID)
{
    $("#User_Name").val(UserID);
};

CPS.getUserEmail = function()
{
    return $("#User_Email").val();
};

CPS.setUserEmail = function(UserID)
{
    $("#User_Email").val(UserID);
};

CPS.getRoleID = function()
{
    return $("#Role_ID").val();
};

CPS.setRoleID = function(roleID)
{
    $("#Role_ID").val(roleID);
};

CPS.getRoleName = function()
{
    return $("#Role_Name").val();
};

CPS.setRoleName = function(roleName)
{
    $("#Role_Name").val(roleName);
};

CPS.getSchoolID = function()
{
    return $("#School_ID").val();
};

CPS.setSchoolID = function(SchoolID)
{
    $("#School_ID").val(SchoolID);
};
CPS.getSchoolName = function()
{
    return $("#School_Name").val();
};

CPS.setSchoolName = function(SchoolName)
{
    $("#School_Name").val(SchoolName);
};




/**
 * Add a temp Container and return the ID
 * Return the id of the div
 * @returns {unresolved}
 */
CPS.AddTempDIV = function()
{
    var id = new Date().getTime();
    var divID = String.format("Div_{0}", id);
    var tmpHtml = String.format("<div id='{0}'></div>", divID);
    if ($("#debugDiv").html().length > 40960) {
        $("#debugDiv").html("");
    }
    $("#debugDiv").append(tmpHtml);
    return divID;
};

CPS.ShowProcessing = function()
{
    var html = "<div id='zLoading'>";
    html += "<div id=\"div_loading\" class=\"Window_Mask_Shadow\"></div>";
    html += "<div id=\"circularG\">";
    html += "<div id=\"circularG_1\" class=\"circularG\"></div>";
    html += "<div id=\"circularG_2\" class=\"circularG\"></div>";
    html += "<div id=\"circularG_3\" class=\"circularG\"></div>";
    html += "<div id=\"circularG_4\" class=\"circularG\"></div>";
    html += "<div id=\"circularG_5\" class=\"circularG\"></div>";
    html += "<div id=\"circularG_6\" class=\"circularG\"></div>";
    html += "<div id=\"circularG_7\" class=\"circularG\"></div>";
    html += "<div id=\"circularG_8\" class=\"circularG\"></div>";
    html += "</div>";
    html += "</div>";
    $("body").append(html);

};


CPS.CloseProcessing = function(doCallback)
{
    var t = window.setTimeout(function() {
        doCallback();
        $("#zLoading").hide();
        $("#zLoading").remove();
        $("#div_loading").hide();
        $("#div_loading").remove();
        $("#circularG").hide();
        $("#circularG").remove();
        window.clearTimeout(t);
    }, 300);




};



/**
 *  To pop up a DIV and a Window
 *  The arguments are [selectorID,width,height,modal(boolean)]
 *  @param {type} divSelectorID
 *  @returns {undefined}
 */
CPS.ShowAsWindow = function(divSelectorID)
{
    if (arguments.length === 1)
    {
        $(divSelectorID).window({
            width: 600,
            height: 400,
            modal: true,
            onClose: function() {
                $(divSelectorID).remove();
            }
        });
    }

    // Set width and height
    if (arguments.length === 3)
    {
        $(divSelectorID).window({
            width: arguments[1],
            height: arguments[2],
            modal: true,
            onClose: function() {
                $(divSelectorID).remove();
            }
        });
    }
    // Set width, height and modal 
    if (arguments.length === 4)
    {
        $(divSelectorID).window({
            width: arguments[1],
            height: arguments[2],
            modal: arguments[3],
            onClose: function() {
                $(divSelectorID).remove();
            }
        });
    }
};


/**
 * Add a new tab and return the pannel object  
 * @param {type} tabTitle
 * @returns panel Object
 */
CPS.addnewTab = function(tabTitle)
{
    if ($('#MainContent').tabs('exists', tabTitle)) {
        $('#MainContent').tabs('select', tabTitle);
        return $('#MainContent').tabs('getTab', tabTitle);
    }

    // if no same ID,then add new Tab with hidden file
    else
    {
        var uid = CPS.getTimeStamp();
        var tabId = String.format("Tab_{0}", uid);
        var innerDivID = String.format("InnerDiv_{0}", uid);
        var closable = true;
        if (arguments.length > 1)
        {
            closable = arguments[1];
        }

        $('#MainContent').tabs('add', {
            title: tabTitle,
            id: tabId,
            content: String.format("<input type='hidden'id='ActionPara' value=''/><div id='{0}'></div>", innerDivID),
            closable: closable,
            selected: false
        }).tabs('select', tabTitle);

        var panel = $('#MainContent').tabs('getTab', tabTitle); // get the selected panel
        panel.tabId = tabId;
        panel.innerDivID = innerDivID;
        panel.paramSelector = String.format("#{0} #{1}", tabId, "ActionPara");
        return panel;
    }

};

/**
 * Add a new tab to accordion
 * @param {String} accordionTitle
 * @param {String} accordionId
 * @returns {Object} like the tab selected element as $(#divID) 
 */
CPS.addAccordion = function(accordionTitle, accordionId)
{
    $('#accordion_left').accordion('add', {
        title: accordionTitle,
        id: accordionId,
        closable: true,
        selected: false
    });
    // get the newcreated panel
    var pp = $('#accordion_left').accordion('getPanel', accordionTitle);
    return pp;
};

CPS.checkLogin = function(UserID, loginFinishedHandler)
{
    CPS.sendRequestToServer("Membership_Login", [UserID], function(data) {
        if (data.Response_ResultCode === "Login_Sucess") {
            CPS.setSessionID(data.Response_SessionID);
            // user Info 
            CPS.setUserID(data.Response_CarriedData.UserID);
            CPS.setUserName(data.Response_CarriedData.UserName);
            CPS.setUserEmail(data.Response_CarriedData.UserEmail);
            //role and School
            CPS.setRoleID(data.Response_CarriedData.RoleID);
            CPS.setRoleName(data.Response_CarriedData.RoleName);
            CPS.setSchoolID(data.Response_CarriedData.SchoolID);
            CPS.setSchoolName(data.Response_CarriedData.SchoolName);

            // call back with data as parameter
            $("#btn_login").remove();
            loginFinishedHandler(data.Response_CarriedData);
        }
        else
        {
            CPS.CloseProcessing(function() {
                CPS.showNotification("Error", "Login Fail");
            });

        }

    });

};

/**
 * Do the Login after 
 * @param {type} loginID
 * @returns {undefined}
 */
CPS.directCheckLogin = function(loginID)
{
    CPS.ShowProcessing();
    CPS.checkLogin(loginID, function(data) {
        var roleid = data.RoleID;
        switch (roleid)
        {
            case "RoleType03":
                {
                    currentController = new Controller_Advisor();
                    currentController.autoGetUpdatesFromServer();
                    currentController.initLeftBar();
                    CPS.CloseProcessing(function() {
                        CPS.showNotification("Sucess", "Login Sucess AS Advisor");
                        CPS.setLoginInfoBar();
                    });

                    break;
                }
            case "RoleType02":
                {
                    currentController = new Controller_Secretary();
                    currentController.autoGetUpdatesFromServer();
                    currentController.initLeftBar();
                    CPS.CloseProcessing(function() {
                        CPS.showNotification("Sucess", "Login Sucess As Sectary");
                        CPS.setLoginInfoBar();
                    });
                    break;
                }
            case "RoleType01":
                {
                    currentController = new Controller_Faculty();
                    currentController.autoGetUpdatesFromServer();
                    currentController.initLeftBar();
                    CPS.CloseProcessing(function() {
                        CPS.showNotification("Sucess", "Login Sucess As Facualty");
                        CPS.setLoginInfoBar();

                    });
                    break;
                }
        }

    });

};

/**
 * POP UP the windows for Check Login
 * @returns {undefined}
 */
CPS.popUpCheckLogin = function()
{
    $.messager.prompt('Prompt', 'Please enter your ID', function(r) {
        if (r) {
            CPS.ShowProcessing();
            CPS.directCheckLogin(r);
        }
    });
};


CPS.EncodeHTML = function(text) {
    return String(text).replace(/["<>& ]/g, function(all) {
        return "&" + {
            '"': 'quot',
            '<': 'lt',
            '>': 'gt',
            '&': 'amp',
            ' ': 'nbsp'
        }[all] + ";";
    });
};





/**
 * Send general resuqst to Server
 * @param {String} requestActionName
 * @param {Object or Array} carriedData
 * @param {function(data)} callback
 * @returns {undefined}
 */
CPS.sendRequestToServer = function(requestActionName, carriedData, callback)
{
    var requestObject = new Object();
    requestObject.requestActionName = requestActionName;
    requestObject.sessionID = this.getSessionID();
    requestObject.carriedData = carriedData;
    Trace.debugJsObject(requestObject);
    Trace.debugJsObject(requestObject.carriedData);
    // send post data to server
    $.post("../Server/Server.php", requestObject, function(data) {
        Trace.debugOutput(data);
        var responseObj = $.parseJSON(data);
        Trace.debugJsObject(responseObj);
        Trace.debugJsObject(responseObj.Response_CarriedData, "#456");
        //return the dataObject
        callback(responseObj);
    }).fail(function(data) {
        Trace.debugFailResponse(data);
    });
};

/**
 * A confirm before actiona
 * @param {String} title
 * @param {String} content
 * @param {function} confirmCallback
 * @returns {undefined} 
 * */
CPS.confirmAction = function(title, content, confirmCallback)
{
    $.messager.confirm(title, content, function(r) {
        if (r) {
            confirmCallback();
        }
    });
};

/**
 * Show a notification
 * @param {type} title
 * @param {type} message
 * @returns {undefined}
 */
CPS.showNotification = function(title, message) {
    var style_TopLeft = {
        right: '',
        left: 0,
        top: document.body.scrollTop + document.documentElement.scrollTop,
        bottom: ''
    };

    var style_Center = {
        right: '',
        bottom: ''
    };

    if (arguments.length === 2) {
        $.messager.show({
            title: title,
            msg: message,
            showType: 'fade',
            timeout: 2000,
            style: style_Center
        });
    }
    // different position
    if (arguments.length > 2)
    {
        if (arguments[2] === 1)
        {
            $.messager.show({
                title: title,
                msg: message,
                showType: 'fade',
                timeout: arguments[3],
                style: style_TopLeft
            });
        }
        // buttom right
        if (arguments[2] === 2)
        {
            $.messager.show({
                title: title,
                msg: message,
                showType: 'fade',
                timeout: arguments[3]
            });
        }
    }
};

//*********************************************
//File Upload Class
//**********************************************

var FileUpload = {};
FileUpload.deleteFile = function(parentContainerSelector, index)
{
    var selector = String.format("{0} #FileToUpLoadBlock_{1}", parentContainerSelector, index);
    // send to server
    $(selector).fadeOut("2000", function() {
        $(selector).remove();
    });
};

FileUpload.uploadFile = function(parentContainerSelector, index)
{
    var serverUrl = "../Server/Server.php";
    // the block selector
    var blockSelector = String.format("{0} #FileToUpLoadBlock_{1}", parentContainerSelector, index);
    var fileInputSelector = blockSelector + " #File_Input";
    var fileProcessSelector = blockSelector + " #uploadProcess";
    var fileDeleteSelector = blockSelector + " #btn_DeleteFile";
    var fileuploadSelector = blockSelector + " #btn_UploadFile";
    var fileUploadProcessInfoSelector = blockSelector + " #processInfo";
    // the finish data    
    var fileNameSelector = blockSelector + " #Lable_FileName";
    var fileMd5Selector = blockSelector + " #File_ServerMd5";
    var fileStateSelector = blockSelector + " #File_State";

    var fileEntity = $(fileInputSelector)[0].files[0];
    var fileName = fileEntity.name;
    var fileSize = fileEntity.size;

    var pos = fileName.lastIndexOf(".");
    var extendtion = fileName.substring(pos, fileName.length);
//    if (extendtion.toLowerCase() !== ".pdf")
//    {
//        CPS.showNotification("Wrong File", "Only PDF File is accepted");
//        $(fileInputSelector).focus();
//        return false;
//    }


    var progressing = function(e) {
        if (e.lengthComputable) {
            var percentComplete = Math.round(e.loaded * 100 / e.total);
            $(fileUploadProcessInfoSelector).html(String.format("{0}%", percentComplete));
            $(fileProcessSelector).attr({value: e.loaded, max: e.total});
        }
    };

    var uploadComplete = function(e) {
        Trace.debugJsObject(e, "#ff0000");
        var objectRes = $.parseJSON(e.target.responseText);
        Trace.debugJsObject(objectRes, "#00ffff");
        Trace.debugJsObject(objectRes.Response_CarriedData, "#000");
        $(fileMd5Selector).val(objectRes.Response_CarriedData.FileID);
        $(fileStateSelector).val(objectRes.Response_CarriedData.StoreState);
        $(fileInputSelector).hide();
        $(fileNameSelector).html(fileName).show();
        $(fileDeleteSelector).show();
        $(fileuploadSelector).hide();
        //CPS.showNotification("Upload", "Upload finished");

    };

    var uploadFailed = function(e) {
        Trace.debugOutput(e);
    };

    var uploadCanceled = function(e) {
        Trace.debugOutput(e);
    };

    var formData = new FormData();
    formData.append("sessionID", CPS.getSessionID());
    formData.append("requestActionName", "Action_File_UpLoad");
    formData.append("fileToUpload", fileEntity);
    formData.append("carriedData", null);

    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener("progress", progressing, false);
    xhr.addEventListener("load", uploadComplete, false);
    xhr.addEventListener("error", uploadFailed, false);
    xhr.addEventListener("abort", uploadCanceled, false);
    xhr.open("POST", serverUrl, true);
    xhr.send(formData);
};


/**
 * Validate the file
 * @param {type} Selector_FileUploadContainer
 * @returns {Array}
 */
FileUpload.Validate = function(Selector_FileUploadContainer)
{
    var Selector_All_Blocks = Selector_FileUploadContainer + " table[name*=\"FileToUpLoadBlock_\"]";
    var fileList = new Array();
    $(Selector_All_Blocks).each(function(index, element) {
        var Selector_FileStatus = Selector_FileUploadContainer + " #" + element.id + " #File_State";
        var Selector_FileID = Selector_FileUploadContainer + " #" + element.id + " #File_ServerMd5";
        var Selector_FileName = Selector_FileUploadContainer + " #" + element.id + " #Lable_FileName";
        if ($(Selector_FileStatus).val() === "true")
        {
            var objFileInfo = {};
            objFileInfo.FileID = $(Selector_FileID).val();
            objFileInfo.FileName = $(Selector_FileName).html();
            fileList.push(String.format("{0}|{1}", objFileInfo.FileID, objFileInfo.FileName));
        }
    });
    return fileList;
};



/**
 * Add a new block to the container
 * @param {type} parentContainerSelector
 * @returns {undefined}
 */
FileUpload.AddNew = function(parentContainerSelector)
{
    var html = "";
    html += "<table style='border: 1px solid;margin-top: 5px;' id='FileToUpLoadBlock_{0}' name='FileToUpLoadBlock_{0}' >";
    html += "<tr>";
    html += "<td><input type='file' id='File_Input'/><label id='Lable_FileName'></lable></td>";
    html += "<td><input id='File_State' type='hidden' value=''/><input id='File_ServerMd5' type='hidden' value=''/></td>";
    html += "</tr>";
    html += "<tr>";
    html += "<td><progress value='0' id='uploadProcess'></progress><label id='processInfo'></label></td>";
    html += "<td>";
    html += "<a href='#'id ='btn_UploadFile'></a>";
    html += "<a href='#'id ='btn_DeleteFile'/></a></td>";
    html += "</tr>";
    html += "</table>";

    var index = $(parentContainerSelector + " #File_Input").size();
    html = String.format(html, index);
    $(parentContainerSelector).append(html);

    // handle the animation and display
    var blockSelector = parentContainerSelector + " #FileToUpLoadBlock_" + index;
    var uploadselector = blockSelector + " #btn_UploadFile";
    var deleteSelector = blockSelector + " #btn_DeleteFile";
    // handle the upload button
    $(uploadselector).linkbutton({
        iconCls: 'icon-save',
        iconAlign: 'left',
        text: 'save'
    }).show().click(function() {
        FileUpload.uploadFile(parentContainerSelector, index);
    });
    // handle delete button
    $(deleteSelector).linkbutton({
        iconCls: 'icon-cancel',
        iconAlign: 'left',
        text: 'Delete'
    }).show().click(function() {
        FileUpload.deleteFile(parentContainerSelector, index);
    });

    $(blockSelector).show();
};

//--------------------------------------------------------------
// From here, it is the datagrid class
//--------------------------------------------------------------
var DataGridComponent = {};
// the instance 's parent
DataGridComponent.ParentContainerSecectorID = null;
DataGridComponent.DataGridSelectorID = null;

/**
 *  Push the Array Data to Data load, only accept Array Data
 * @param {type} data
 * @returns {undefined} */
DataGridComponent.LoadData = function(data)
{
    $(this.DataGridSelectorID).datagrid('loadData', data);
};

/**
 * Init the basic Data Grid with Header Config
 * @param {type} parentContainerID
 * @param {type} headerArray
 * @returns {undefined}
 */
DataGridComponent.Init = function(parentContainerID, headerArray)
{
    this.ParentContainerSecectorID = parentContainerID;
    this.DataGridSelectorID = String.format("{0} {1}", parentContainerID, "#datagrid");
    $(this.ParentContainerSecectorID).append("<table id ='datagrid'style='max-height: 300px'></table>");
    var pagerFilter = function(data) {
        if (typeof(data.length) === "number" && typeof (data.splice) === "function") {	// is array
            data = {
                total: data.length,
                rows: data
            };
        }
        var dg = $(this);
        var opts = dg.datagrid('options');
        var pager = dg.datagrid('getPager');
        pager.pagination({
            onSelectPage: function(pageNum, pageSize) {
                opts.pageNumber = pageNum;
                opts.pageSize = pageSize;
                pager.pagination('refresh', {
                    pageNumber: pageNum,
                    pageSize: pageSize
                });
                dg.datagrid('loadData', data);
            },
            onRefresh: function(pageNumber, pageSize)
            {
                var tabId = $('#MainContent').tabs('getSelected').panel("options").id;
                var paraActionselector = String.format("#{0} {1}", tabId, "#ActionPara");
                var strAction = $(paraActionselector).val();
                CPS.parseActionString(strAction);
            }
        });
        if (!data.originalRows) {
            data.originalRows = (data.rows);
        }
        var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
        var end = start + parseInt(opts.pageSize);
        data.rows = (data.originalRows.slice(start, end));
        return data;
    };

    // build the data grid
    $(this.DataGridSelectorID).datagrid({
        remoteSort: false,
        singleSelect: true,
        nowrap: false,
        fitColumns: true,
        pagination: true,
        loadFilter: pagerFilter,
        columns: headerArray,
        width: "100%",
        height: $(parentContainerID).parent().panel("options").height - 1,
        maxHeight: 600
    });

};

/**
 * Set the Row Styler
 * @param {type} displayRowStyler
 * @returns {undefined}
 */
DataGridComponent.SetRowStyler = function(displayRowStyler) {
    $(this.DataGridSelectorID).datagrid({
        rowStyler: displayRowStyler
    });
};



/**
 * Set the Detailview
 * @param {type} formatter
 * @param {type} eventHandler
 * @returns {undefined}
 */
DataGridComponent.SetDetailviewWithExpandEvent = function(formatter, eventHandler) {
    $(this.DataGridSelectorID).datagrid({
        view: detailview,
        detailFormatter: formatter,
        onExpandRow: eventHandler
    });
};

/**
 * The mailer Object start from here
 * @type Object
 */
var Mailer = new Object();
Mailer.Application_SendEmailByClickingName = function() {
    var toEmailAddress = arguments[1];
    var html = "<table ID = 'EmailDialog'>";
    html += "<tr><th>To:</th><td>{0} &nbsp &nbsp &#60{1}&#62</td></tr>";
    html += "<tr><th>From:</th><td>{2} &nbsp &nbsp &#60{3}&#62</td></tr>";
    html = String.format(html, arguments[0], arguments[1], arguments[2], arguments[3]);
    html += "<tr><th>Subject:</th><td><input type = 'text' id = 'EmailSubjectInput'></td></tr>";
    html += "<tr><td colspan = '2'><textarea id='EmailBodyInput' style='width:380px;height: 220px'>";
    html += "</textarea></td></tr>";
    html += "<tr><td colspan = '2' style='text-align: center'><button id='sendEmailBtn'>Send</button></td></tr></table>";

    var tempDivSelector = "#" + CPS.AddTempDIV();
    CPS.ShowAsWindow(tempDivSelector, 420, 390, true);
    $(tempDivSelector).panel({
        title: "Email",
        content: html
    });

    var subjectSelector = String.format("{0} {1}", tempDivSelector, "#EmailSubjectInput");
    var emailBodySelector = String.format("{0} {1}", tempDivSelector, "#EmailBodyInput");
    $(subjectSelector).validatebox({
        required: true,
        validType: ['string', 'length[0,40]']
    });
    $(emailBodySelector).validatebox({
        required: true
    });

    var sendBtnSelector = String.format("{0} {1}", tempDivSelector, "#sendEmailBtn");
    $(sendBtnSelector).click(function() {
        CPS.ShowProcessing();
        if (!$(subjectSelector).validatebox('isValid'))
        {

            CPS.CloseProcessing(function() {
                CPS.showNotification("ERROR", "Subject cannot be empty and should be less than 40 letters!");
            });
            return;
        }
        if (!$(emailBodySelector).validatebox('isValid'))
        {

            CPS.CloseProcessing(function() {
                CPS.showNotification("ERROR", "Message body cannot be empty!");
            });
            return;
        }
        var emailObj = new Email_Entiry();
        emailObj.EmailAddress = toEmailAddress;
        emailObj.Subject = $(subjectSelector).val();
        emailObj.Body = $(emailBodySelector).val();
        CPS.sendRequestToServer("sendEmailByClickingName", emailObj, function(data) {
            $(tempDivSelector).window('close');
            CPS.CloseProcessing(function() {
                if (data.Response_ResultCode === "Sucess") {
                    CPS.showNotification("Sucess", "The Email has been  sent successfully!");
                } else {
                    CPS.showNotification("Fail", "Sent Fail! Please contact your administrator!");
                }
            });
        });

    });

};